package com.ruoyi.yuyuan.Service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.yuyuan.DTO.CommentDTO;
import com.ruoyi.yuyuan.DTO.Result;
import com.ruoyi.yuyuan.Entity.*;
import com.ruoyi.yuyuan.Event.EventProducer;
import com.ruoyi.yuyuan.Mapper.CommentMapper;
import com.ruoyi.yuyuan.Mapper.DailyBlogMapper;
import com.ruoyi.yuyuan.Mapper.UserMapper;
import com.ruoyi.yuyuan.Service.ICommentService;
import com.ruoyi.yuyuan.Service.ILikeService;
import com.ruoyi.yuyuan.Utils.IdGenerator;
import com.ruoyi.yuyuan.Utils.MyUtils;
import com.ruoyi.yuyuan.Utils.RedisConstants;
import com.ruoyi.yuyuan.Utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static com.ruoyi.yuyuan.Utils.CommunityConstant.*;

/**
 * @Author: kestrel
 * @Version:1.0
 * @Date: 2024/5/29
 */
@Slf4j
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private DailyBlogMapper dailyBlogMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ILikeService likeService;

    @Autowired
    private MyUtils myUtils;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result comment(CommentDTO commentDTO, Long blogId, Long targetId) {
        Long userId = UserHolder.getUser().getId();
        User user = userMapper.selectById(userId);
        //生成Comment对象
        Comment comment = BeanUtil.copyProperties(commentDTO, Comment.class);

        // 触发评论通知事件
        long receiveId;
        String name = userMapper.selectById(userId).getName();
        if(targetId == 0){
            // targetId = 0 回复帖主
            receiveId = dailyBlogMapper.selectById(blogId).getUserId();
        } else {
            // 回复targetId
            receiveId = targetId;
        }
        Notice notice = new Notice(idGenerator.nextNoticeId(),blogId,userId,receiveId,LocalDateTime.now(),
                "comment","用户" + name + "在帖子" + blogId + "向您评论:" + comment.getContent());
        Event event = new Event(
                TOPIC_COMMENT,
                UserHolder.getUser().getId(),
                ENTITY_TYPE_COMMENT,
                blogId,
                notice,
                "Notice");
        eventProducer.fireEvent(event);


        comment.set(idGenerator.nextCommentId(),blogId,2,targetId,user);
        //保存数据库
        commentMapper.insert(comment);
        //更新博客数据库评论数量(+1)
        UpdateWrapper<BlogDaily> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", blogId).setSql("comments = comments + 1");
        dailyBlogMapper.update(null, updateWrapper);

        // 缓存分数状态变更帖子id
        redisTemplate.opsForSet().add(RedisConstants.getPostScoreKey(), blogId);

        //返回结果
        return Result.ok("评论成功!");
    }

    @Override
    public Result getPageComment(Long blogId, Long startId) {
        //分页查询传入0时默认读取最新(最迟创建)数据，进行处理
        startId = myUtils.zeroHandler(startId, blogId, "Comment");
        List<Comment> list = null;
        if(startId != 0){
            list = commentMapper.getPageByBlogId(blogId, startId);
            for (Comment comment : list) {
                comment.setIfLike(likeService.checkIfLike(UserHolder.getUser().getId(), blogId));
                comment.handlerImgs();
                if(comment.getTargetId()!=0){
                    comment.setTargetName(userMapper.selectById(comment.getTargetId()).getName());
                }
            }
        }
        long len = 0;
        if(list != null) len = list.size();
        //返回结果以及长度
        return Result.ok(list, len);
    }
}
